/*
 * @Description:
 * @version:
 * @Author: 尹鹏孝
 * @Date: 2023-07-08 16:27:54
 * @LastEditors: 尹鹏孝
 * @LastEditTime: 2023-10-10 09:48:27
 */
import { Body, Controller, Get, Post, Req, Res, Param, UseGuards, Session, Inject } from "@nestjs/common";
import { Module } from '@nestjs/common';
import { Repository } from 'typeorm';
import { User } from '../entity/user.entity';
import { Login } from '../entity/login.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { LoginService } from './login.service'
import { AuthService } from './../auth/auth.service';
import { LocalStrategy } from "src/auth/local.strategy";
import { Buffer } from 'node:buffer'
const svgCaptcha = require('svg-captcha');
const captchaPng = require('captchapng')
// let codePng = ''

@Controller()
export class LoginController {

  constructor(
    // @InjectRepository(User)
    private readonly userRepository: LoginService,
    private readonly authService: AuthService,
  ) {

   }
  //生成校验码
  @Get('code')
  code(@Res() res, @Session() session) {
    try {
      const { data,text } = svgCaptcha.createMathExpr({
              size: 4, // 验证码长度
              width:160,
              height:60,
              fontSize: 50,
              ignoreChars: '0oO1ilI', // 验证码字符中排除 0o1i
              noise: 4, // 干扰线条的数量
              color: true, // 验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
              background: "#f3130e",// 验证码图片背景颜色
        })
      //定义session的标识值
      //console.log('session',session)
      session.code = text
      // res.type('image/svg+xml'),
      let img = Buffer.from(data).toString("base64")
      let base64Img = "data:image/svg+xml;base64," + img;
      // res.send(captcha.data)
      res.send(base64Img)
    } catch (error) {
      console.log(error)
      res.send({})
    }
  }
  @Get('pngCode')
  pngCode(@Res() res, @Session() session) {
    try {
      let value  =(Math.random()*2000).toFixed(0)
      let value1 = value;
      let code = value1;
      session.code = code;//保存在session中，便于之后的验证码判断
      //console.log(' session.age:', session.code)

      let p = new captchaPng(100, 30, code);
      p.color(0, 0, 0, 0);
      p.color(80, 80, 80, 255);
      let img = p.getBase64();
      let imgBase64 = `data:image/png;base64,${img}`;
       //console.log('生成code前：',session)
      res.end(imgBase64);
    } catch (error) {
       //console.log(session)
        res.send({})
      }
  }
	//保存
  @UseGuards(LocalStrategy)
  @Post('login')
  public async login(@Body() body: any, @Session() session:any) {
    const { username, password } = body;
    console.log(body)
    try {
       // 前端传回来的验证码，转换成小写
      let age = ''
      // if (session.code&&session.code.length) {

      // } else {
      //   return {
      //       code: 400,
      //       msg: "验证码过期，请刷新重试",
      //       data: {}
      //     }
      // }
      console.log('b-',body)
      console.log(session)
      if (body.age) {
         age= String(body.age).toLowerCase()
      } else {
         return {
            code: 400,
            msg: "验证码不能为空",
            data: {}
          }
      }
      //get方式获取的验证码定义的
      const code = String(session.code).toLowerCase()
      console.log(age)
      console.log(code)

        if (age === code) {
        const result = await this.authService.validateUser(username, password);
          if (result) {
            session.code = null;
            console.log('输出用户：result',result)
            return {
                code: 0,
                message: '成功',
                token: this.authService.certificate({ ...result, password }),  // 签发token
            };
        }
        return {
            code: 1,
            message: '失败',
            detail:'用户名或者密码不对'
        };

        } else {
          return {
            code: 200,
            msg: "验证码错误",
            data: {}
          }
        }
    } catch (error) {
      console.log(error);
       return {
            code: 500,
            msg: error,
            data: {}
          }
    }
  }

  @UseGuards(LocalStrategy)
  @Post('loginWX')
  public async loginWX(@Body() body: any) {
    const { username, password } = body;
    console.log(username)
    console.log(password)
    try {
      const result = await this.authService.validateUser(username, password);
      console.log('result__', result)

      if (result) {


        const user = await this.userRepository.findOneUser({ username, password })
        console.log('user:',user)
            return {
                code: 0,
                message: '成功',
                token: this.authService.certificate({ username, password }),  // 签发token
              user: {
                ...user.user,
                password:''
                },
            };
        }
        return {
            code: 1,
            message: '失败',
            detail:'用户名或者密码不对'
        };
    } catch (error) {
      console.log(error);
       return {
            code: 500,
            msg: error,
            data: {}
          }
    }
  }
  @UseGuards(LocalStrategy)
  @Post("register")
  public async register(@Body() body: any): Promise<any> {
    console.log('111',body)
    return await this.userRepository.registerUser(body);
  }

  @Post("registerWX")
  public async registerWX(@Body() body: any): Promise<any> {
    console.log('111',body)
    return await this.userRepository.registerUserWX(body);
  }
}

